import React from 'react';
import echarts from 'echarts';
// import geoJson from 'echarts/map/json/china.json';
import 'echarts/map/js/world';
import 'echarts/map/js/china';
import 'echarts/map/js/province/anhui.js';
import 'echarts/map/js/province/aomen.js';
import 'echarts/map/js/province/beijing.js';
import 'echarts/map/js/province/chongqing.js';
import 'echarts/map/js/province/fujian.js';
import 'echarts/map/js/province/gansu.js';
import 'echarts/map/js/province/guangdong.js';
import 'echarts/map/js/province/guangxi.js';
import 'echarts/map/js/province/guizhou.js';
import 'echarts/map/js/province/hainan.js';
import 'echarts/map/js/province/hebei.js';
import 'echarts/map/js/province/heilongjiang.js';
import 'echarts/map/js/province/henan.js';
import 'echarts/map/js/province/hubei.js';
import 'echarts/map/js/province/hunan.js';
import 'echarts/map/js/province/jiangsu.js';
import 'echarts/map/js/province/jiangxi.js';
import 'echarts/map/js/province/jilin.js';
import 'echarts/map/js/province/liaoning.js';
import 'echarts/map/js/province/neimenggu.js';
import 'echarts/map/js/province/ningxia.js';
import 'echarts/map/js/province/qinghai.js';
import 'echarts/map/js/province/shandong.js';
import 'echarts/map/js/province/shanghai.js';
import 'echarts/map/js/province/shanxi.js';
import 'echarts/map/js/province/shanxi1.js';
import 'echarts/map/js/province/sichuan.js';
import 'echarts/map/js/province/taiwan.js';
import 'echarts/map/js/province/tianjin.js';
import 'echarts/map/js/province/xianggang.js';
import 'echarts/map/js/province/xinjiang.js';
import 'echarts/map/js/province/xizang.js';
import 'echarts/map/js/province/yunnan.js';
import 'echarts/map/js/province/zhejiang.js';

import { geoCoordMap, provienceData, cityData } from './js/geo';

import './App.css';


class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      activeMap: '上海',
    };
    this.myChart = null;
  }

  componentDidMount() {
    this.initEcharts();
  }

  initEcharts = () => {
    // echarts.registerMap('北京', geoJson);
    this.myChart = echarts.init(document.getElementById('mainMap'));
    // this.setEchartOption(this.myChart);
    this.mapSetOption();
    // 绑定地图的click事件，可以拿到地图省份信息，散点信息等。如果是省级地图，可以拿到市一级信息
    this.myChart.on('click', this.onClickMap);
  }

  mapSetOption = () => {
    this.myChart.setOption({
      geo: {
        map: this.state.activeMap, // china，world，中文省名
        zoom: 1, //当前视角的缩放比例
        roam: true, // 允许鼠标滚轮放缩地图
        scaleLimit: { //滚轮缩放的极限控制
          min: 1,
          max: 3
        },
        itemStyle: {                    // 定义样式
          normal: {                    // 普通状态下的样式
            areaColor: '#ddd',
            borderColor: '#111'
          },
          emphasis: {                    // 高亮状态下的样式
            areaColor: '#888'
          }
        }
      },
      backgroundColor: '#404a59', // 设置地图背景
      series: [
        {
          name: '销量', // series名称
          type: 'scatter', // series图表类型 散点图
          coordinateSystem: 'geo', // series坐标系类型
          data: this.getMockScatterData(),
        },
        // {
        //   type: "map",
        //   // map: this.state.activeMap,
        //   // center: [104.114129, 37.550339],//当前视角的中心点
        //   zoom: 1, //当前视角的缩放比例
        //   roam: true, //是否开启平游或缩放
        //   scaleLimit: { //滚轮缩放的极限控制
        //     min: 1,
        //     max: 2
        //   },
        // }
      ],
      visualMap: { // 视觉映射组件
        type: 'continuous', // 连续型
        min: 0,               // 值域最小值，必须参数
        max: 1000,            // 值域最大值，必须参数
        calculable: true,    // 是否启用值域漫游
        inRange: {
          color: ['#ff8080', '#660000']
          // 指定数值从低到高时的颜色变化
        },
        textStyle: {
          color: '#fff'    // 值域控件的文本颜色
        }
      }
    });
  }

  isCityOfProvience = (city, provience) => {
    console.log('isCityOfProvience', city, provience);
    if (provience === 'china') {
      console.log('true');
      return true;
    }
    const findProv = cityData.find((provItem) => provItem.provinceName.includes(provience));
    const findCity = findProv ? findProv.citys.find((cityItem) => cityItem.citysName.includes(city)) : null;
    return Boolean(findCity);
  }

  getRadomData = () => {
    let cityArr = [];
    const max = 1000;
    const min = 0;
    // 有优化空间，先根据省再市
    // geoCoordMap 增加省份信息以提升效率
    for (const key in geoCoordMap) {
      if (geoCoordMap.hasOwnProperty(key)) {
        let randomValue = Math.random() * (max - min) + min;
        // 只提取当前省的城市数据
        if (this.isCityOfProvience(key, this.state.activeMap)) {
          cityArr.push({
            name: key,
            value: geoCoordMap[key].concat([Math.floor(randomValue)])
          })
        }
      }
    }
    // console.log(cityArr);
    return cityArr;
  }

  getMockScatterData = () => {
    // {
    //   name: '北京',    // 数据项名称，在这里指地区名称
    //   value: [        // 数据项值
    //     116.46,     // 地理坐标，经度
    //     39.92,      // 地理坐标，纬度
    //     340         // 北京地区的数值
    //   ]
    // }
    let mockData = this.getRadomData();
    return mockData;
  }

  setEchartOption = (chart) => {
    chart.setOption({
      tooltip: {
        show: false,       //不显示提示标签
        formatter: '{b}',      //提示标签格式
        backgroundColor: "#ff7f50",//提示标签背景颜色
        textStyle: { color: "#fff" } //提示标签字体颜色
      },
      grid: {
        left: '10%',
        right: '10%',
        top: '10%',
        bottom: '10%',
        containLabel: true
      },
      geo: {
        map: 'china',
        roam: false,
        zoom: 1.2,
        tooltip: {
          show: false,       //不显示提示标签
        },
        label: {
          normal: {
            show: false,//显示省份标签
            textStyle: { color: "#000" }//省份标签字体颜色
          },
          emphasis: {//对应的鼠标悬浮效果
            show: true,
            textStyle: { color: "#FF0000" }
          }
        },
        itemStyle: {
          normal: {
            borderWidth: .5,//区域边框宽度
            borderColor: '#fff',//区域边框颜色
            areaColor: "#ffefd5",//区域颜色
            label: { show: false }
          },
          emphasis: {
            show: false,
            borderWidth: .5,
            borderColor: '#4b0082',
            areaColor: "#ffdead",
          }
        },
      },
      series: [
        {
          type: 'scatter',
          coordinateSystem: 'geo',
          // data: this.convertData(data),
          symbolSize: 20,
          symbolRotate: 35,
          label: {
            normal: {
              formatter: '{b}',
              position: 'right',
              show: true
            },
            emphasis: {
              show: false
            }
          },
          tooltip: {
            show: false,       //不显示提示标签
            formatter: '{c}',      //提示标签格式
            backgroundColor: "#fff",//提示标签背景颜色
            borderColor: '#ccc',
            borderWidth: .5,
            textStyle: { color: "#000" } //提示标签字体颜色
          },
          itemStyle: {
            normal: {
              color: '#F00'
            }
          }
        },
        {
          type: 'map',
          mapType: 'china',
          roam: false,
          zoom: 1.2,
          tooltip: {
            show: false,       //不显示提示标签
          },
          label: {
            normal: {
              show: true    //显示省份标签
            },
            emphasis: {
              show: true,
              color: '#f00'
            }
          },
          itemStyle: {
            normal: {
              borderWidth: .5,      //区域边框宽度
              borderColor: 'rgb(32, 42, 129)',  //区域边框颜色
              label: { show: false }
            },
            emphasis: {
              show: false,
            }
          },
          // geoIndex: 0,
          // tooltip: {show: false},
          // data: provienceData
        }
      ],
    })
  }

  onClickMap = (params) => {
    console.log('myChart click', params);
    
    const found = provienceData.find((item) => item.name === params.name);
    if (found) {
      this.setMap(params.name);
    }
  }

  onClickBackBtn = () => {
    // alert('go back');
    this.setMap('china');
  }

  setMap = (map) => {
    console.log('setMap', map);
    if (map === '南海诸岛') {
      // 南海诸岛 没有地图
      return;
    }
    this.setState({ activeMap: map }, () => {
      this.mapSetOption();
    });
  }

  onClickMapBtn = () => {
    const myPool = [...provienceData, {name: 'china'}, {name: 'world'}];
    const max = myPool.length - 1;
    const min = 0;
    const randomIdx = Math.floor(Math.random() * (max - min) + min);
    this.setMap(myPool[randomIdx].name);
  }

  render() {
    return (
      <div className="App">
        <div id="mainMap" className="mainMap"></div>
        <div className="topTitleContainer">
          <h3 className="activeMap">{this.state.activeMap === 'china' ? '全国' : this.state.activeMap}</h3>
        </div>
        <div className="topContainer">
          <button className="btnBack" onClick={() => {this.onClickBackBtn()}}>Go Back</button>
          <button className="btnMap" onClick={() => { this.onClickMapBtn() }}>Random Map</button>
        </div>
      </div>
    )
  }
}


export default App;
